package com.example.springquartzsample;

import com.example.springquartzsample.scheduler.TestDynamicJob;
import com.example.springquartzsample.scheduler.dynamic.DynamicJob;
import com.example.springquartzsample.scheduler.dynamic.DynamicSchedulerFactory;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping
public class SchedulerController {

    Logger log = LoggerFactory.getLogger(SchedulerController.class);
    @RequestMapping(value = {"add"},method = {RequestMethod.GET})
    public String add(){
        DynamicJob dynamicJob = createDynamicJob();
        //transfer parameter
        dynamicJob.addJobData("mailGuid", UUID.randomUUID().toString());
        try {
            boolean ok = DynamicSchedulerFactory.registerJob(dynamicJob);
            log.info("Register DynamicJob [{}] -> {}", dynamicJob, ok);
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }
        return "添加完成";
    }

    @RequestMapping(value = {"remove"},method = {RequestMethod.GET})
    public String remove(){
        final DynamicJob dynamicJob = createDynamicJob();
        try {
            final boolean result = DynamicSchedulerFactory.removeJob(dynamicJob);
            log.info("Remove DynamicJob [{}] result: {}", dynamicJob, result);
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }
        return "添加完成";
    }
    /**
     * 创建 一个动态的JOB, 测试用
     */
    private DynamicJob createDynamicJob() {
        return new DynamicJob("test-")
                //动态定时任务的 cron,  每20秒执行一次
                .cronExpression("0/20 * * * * ?")
                .target(TestDynamicJob.class);
    }
}
